package Internet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

//网络编程,Socket使用
public class Test1 {
    public static void main(String[] args) throws InterruptedException {
        Server server = new Server();
        server.start();
        Client client = new Client();
        client.start();
    }
}
class Server extends Thread{//服务器类
    @Override
    public void run() {
        try {
            Scanner scanner = new Scanner(System.in);
            ServerSocket waitSocketConnection = new ServerSocket(9000);//服务器建立ServerSocket对象等待客户请求,ServerSocket()参数客户机发送的端口号9000

            Socket accept = waitSocketConnection.accept();//调用accept()接受客户机请求,当有请求建立时返回Socket对象accept,否则不会返回会阻塞线程
            System.out.println("连接已建立");
            OutputStream outputStream = accept.getOutputStream();//创建一个输出流指向客户机,向对方输出
            System.out.println("请输入发送的字符串");
            String s = scanner.nextLine();
            byte[] bytes = s.getBytes();
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
class Client extends Thread{//客户机类
    @Override
    public void run() {
        try {
            System.out.println("请求建立连接");
            Socket socket = new Socket("192.168.1.172",9000);//客户端创建Socket对象,构造方法("服务器地址",连接端口号)，当连接建立成功后返回Socket对象socket
            InputStream inputStream = socket.getInputStream();//创建输入流,获取服务器的输入
            Thread.sleep(3000);
            byte[] bytes = inputStream.readAllBytes();
            System.out.println("客户端收到数据"+ new String(bytes));
            inputStream.close();
        } catch (InterruptedException | IOException e) {
                e.printStackTrace();
            }

    }
}